
package com.hyst.seviceImpl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;
import com.hyst.common.ResultBean;
import com.hyst.domain.PurchaseCourseView;
import com.hyst.repository.RecommendMsgMapper;
import com.hyst.service.PurchaseCourseService;
import com.hyst.utils.StringUtils;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hyst.domain.CurriculumScheduleView;
import com.hyst.domain.Student;
import com.hyst.domain.StudentView;
import com.hyst.repository.CurriculumScheduleMapper;
import com.hyst.repository.StudentMapper;
import com.hyst.service.CurriculumScheduleService;
import com.hyst.service.StudentService;
import com.hyst.utils.UuidTool;

/**
 * @Description:
 * @Date：2018年08月25日 @author： dy
 * @version ：1.0 1.[2018年08月25日]
 */
@Service
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentMapper mapper;
	@Autowired
	private CurriculumScheduleMapper csmapper;
	@Autowired
	CurriculumScheduleService csService;

	@Autowired
	private PurchaseCourseService purchaseCourseService;

	@Autowired
	private RecommendMsgMapper recommendMsgMapper;

	@Override
	public Page<StudentView> listview(final StudentView studentView) {
		List<String> stuIds = new ArrayList<>();
		if (studentView.getType() != null ) {
			//微信
			stuIds = getStuByType(studentView.getType());
		}

		final Page<StudentView> page = PageHelper.startPage(studentView.getPageNum(), studentView.getPageSize());
		try {
			if (stuIds.size() == 0) {
				if (org.apache.commons.lang3.StringUtils.isNotBlank(studentView.getStudentId())) {
					mapper.getFreeListen3(studentView.getStudentId());
				} else {
					mapper.getFreeListen2();
				}
			} else {
				mapper.getFreeListen(stuIds);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}


		for (StudentView studentView1 : page.getResult()) {
			PurchaseCourseView view = new PurchaseCourseView();
			view.setStudentId(studentView1.getStudentId());
			Page<PurchaseCourseView> byStudent = purchaseCourseService.getByStudent(view);
			String statusUnBegin = "";
			String statusUnFinish = "";
			for (PurchaseCourseView purchaseCourseView : byStudent.getResult()) {
				if (org.apache.commons.lang3.StringUtils.isNotBlank(purchaseCourseView.getEventsWay()) && !purchaseCourseView.getEventsWay().contains("试听")) {
					if (1 == purchaseCourseView.getState()) {
						statusUnBegin = "进行中";
						break;
					}else {
						statusUnFinish = "已完成";
					}
				}
			}

			if (org.apache.commons.lang3.StringUtils.isNotBlank(statusUnBegin)) {
				studentView1.setStatus(statusUnBegin);
			} else if (org.apache.commons.lang3.StringUtils.isNotBlank(statusUnFinish)) {
				studentView1.setStatus(statusUnFinish);
			}
		}
		return page;
	}

	@Override
	public Student insert(final Student student) {
		student.setStudentId(UuidTool.randomUUID());
		mapper.insertSelective(student);
		return student;
	}

	@Override
	public Student getByPriKey(final String studentId) {
		final Student student = mapper.selectByPrimaryKey(studentId);
		return student;
	}


	@Override
	public ResultBean saveDelete(final String studentId) {
//		mapper.saveDelete(studentId);
		mapper.deleteStudent(studentId);

		//释放课程
        mapper.deletePeriod(studentId);
		return ResultBean.success("");
	}



	@Override
	public Student updateSelective(final Student student) {
		System.out.print("-------------");
		mapper.updateByPrimaryKeySelective(student);
		return student;
	}

	@Override
	public Student update(final Student student) {
		mapper.updateByPrimaryKey(student);
		return student;
	}

	@Override
	public Student delete(final String studentId) {

		return null;
	}

	@Override
	public Page<Student> list(final Student student) {
		final Page<Student> page = PageHelper.startPage(student.getPageNum(), student.getPageSize());
		mapper.getTryListenStudent();
		return page;
	}

	@Override
	public List<Map> getSelect2Data() {
		return mapper.getSelect2Data();
	}


	@Override
	public List<Map> getSelect3Data() {
		return mapper.getSelect3Data();
	}

    @Override
    public List<Map> getSelect4Data(String key) {
        return mapper.getSelect4Data(key);
    }

	
	@Override
	public Page<StudentView> getDataByCondition(final StudentView studentView,String condition) {
		final Page<StudentView> page = PageHelper.startPage(studentView.getPageNum(), studentView.getPageSize());
		if(condition==""){
			condition=null;
		}
		StudentView student = new StudentView();
		student.setEnName(condition);//暂时只对英文名字模糊查询，后续可修改
		mapper.getListByCondition(student);
		return page;
	}
	
	@Override
	public Page<StudentView> getDataByFuzerenId(final StudentView studentView,String condition) {
		final Page<StudentView> page = PageHelper.startPage(studentView.getPageNum(), studentView.getPageSize());
		if(condition==""){
			condition=null;
		}
		String []a=condition.split("&");
		StudentView student = new StudentView();
		if( (!a[0].equals("all")) && (!a[1].equals("all"))){
			student.setFuzerenId(a[0]);
			student.setTryListenstate(a[1]);
		}
		else{
			if(!a[0].equals("all")){
				student.setFuzerenId(a[0]);
			}
			if(!a[1].equals("all")){
				student.setFuzerenId(a[1]);
			}			
		}
		mapper.getListFuzerenId(student);
		return page;
	}
	
	
	@Override
	public Student saveAllotData(final String studentId) {
		System.out.println(studentId);
		String []a=studentId.split("&");
		StudentView student = new StudentView();
		student.setStudentId(a[0]);
		student.setFuzerenId(a[1]);
		mapper.saveAllotData(student);
		return null;
	}
	
	
	
	@Override
	public Student saveRemark(final String studentId) {
		System.out.println(studentId);
		String []a=studentId.split("&");
		StudentView student = new StudentView();
		student.setStudentId(a[0]);
		student.setComments(a[1]);
		if(student.getComments().equals("不报课") || student.getComments().equals("正式报课")){
//			final Map recommend = mapper.getRecommend(Long.valueOf(studentId));
//			final HashMap<Object, Object> objectObjectHashMap = Maps.newHashMap();
//			objectObjectHashMap.put("recommender",recommend.get("studentId"));
//			objectObjectHashMap.put("studentId",recommend.get("recommend"));
//			objectObjectHashMap.put("status",student.getStatus());
//			recommendMsgMapper.updateStatus(objectObjectHashMap);
		}
		mapper.saveRemarkData(student);
		return null;
	}
	
	@Override
	public Student savestateEdit(final String studentId) {
		System.out.println(studentId);
		String []a=studentId.split("&");
		StudentView student = new StudentView();
		student.setStudentId(a[0]);
		student.setTryListenstate(a[1]);
		mapper.savestateEditData(student);
		return null;
	}
	
	@Override
	public Student savedoDelete(final String studentId) {
		System.out.println(studentId);
		StudentView student = new StudentView();
		student.setStudentId(studentId);
		student.setIsdeleted(1);
		mapper.savedoDeleteData(student);
		return null;
	}

	@Override
	public StudentView getStuInfo(String studentId) {
		try {
			StudentView stuInfo = mapper.getStuInfo(studentId);
			if(org.apache.commons.lang3.StringUtils.isNotBlank(stuInfo.getCreateTime())){
				stuInfo.setCreateTime(stuInfo.getCreateTime().replace(".0",""));
			}
			BigDecimal sumMoney = mapper.getSumMoney(studentId);
			if (sumMoney != null) {
				stuInfo.setTotalMoney(sumMoney.setScale(2));
			} else {
				stuInfo.setTotalMoney(BigDecimal.ZERO.setScale(2));
			}

			Student student=mapper.getById(studentId);
			if(student!=null && org.apache.commons.lang3.StringUtils.isNotBlank(student.getZoomId())){
				stuInfo.setZoomId(student.getZoomId());
			}

			String headImgUrl = mapper.getHeadImgUrl(stuInfo.getPhone());
			if (org.apache.commons.lang3.StringUtils.isNotBlank(headImgUrl)) {
				stuInfo.setHeadImgUrl(headImgUrl);
			}else {
                stuInfo.setHeadImgUrl("../../static/img/student.jpg");
            }

			return stuInfo;
		} catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String leave(String phone, String startDate, String endDate) throws ParseException, CloneNotSupportedException {
		Student student=mapper.getByPhone(phone);
		Map<String, String> map=new HashMap<>();
		map.put("studentId", student.getStudentId());
		map.put("start", startDate);
		map.put("end", endDate);
		List<CurriculumScheduleView> list=csmapper.getStudentLeval(map);
		for(CurriculumScheduleView cs:list){
			System.out.println(cs);
			csService.addLevalClass(cs.getPurchaseCourseId(), cs.getClassLength(),null);
		}
		return null;
	}

	private List<String> getStuByType(Integer type) {
		List<String> stuids = new ArrayList<>();
		List<StudentView> students = mapper.getAll();

		if (type == 1) {
			for (StudentView student : students) {
				String phone = student.getPhone();
				if (org.apache.commons.lang3.StringUtils.isNotBlank(phone)) {
					int count = mapper.getCountWeChatApp(phone) + mapper.getCountWeChatMp(phone);
					if (count <= 0) {
						stuids.add(student.getStudentId());
					}
				}
			}
		} else if (type == 2) {
			for (StudentView student : students) {
				if (org.apache.commons.lang3.StringUtils.isBlank(student.getWechat())) {
					stuids.add(student.getStudentId());
				}
			}
		}
		return stuids;
	}



	@Override
	public ResultBean weixinBindStatics() {
		Map<String, Object> result = new HashMap<>();
		try {
			List<StudentView> noBindWixin = new ArrayList<>();
			List<StudentView> noRegistWeixin = new ArrayList<>();
			List<StudentView> students = mapper.getAll();
			for (StudentView student : students) {
				if (org.apache.commons.lang3.StringUtils.isBlank(student.getWechat())) {
					noRegistWeixin.add(student);
				}
				String phone = student.getPhone();
				if (org.apache.commons.lang3.StringUtils.isNotBlank(phone)) {
					int count = mapper.getCountWeChatApp(phone) + mapper.getCountWeChatMp(phone);
					if (count <= 0) {
						noBindWixin.add(student);
					}
				}
			}
			result.put("noBindWixin", noBindWixin);
			result.put("noRegistWeixin", noRegistWeixin);
		} catch (Exception e){
			e.printStackTrace();
		}
		return ResultBean.success(result);
	}
}
